package com.sgb.kjwl.view.ui.activity.self.packers;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ScreenUtils;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtSelfWorkExperienceBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.self.SelfWorkerPublishEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.NumberConstant;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.sgb.link.view.adapter.SelfTeamPicAdapter;

import com.sgb.kjwl.viewmodel.self.packers.SelfWorkExperienceModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;

/**
 * @author liwei
 * @date 2020/12/19
 * description:工作经验和资格证书
 */
public class SelfWorkExperienceActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    @Inject
    SelfWorkExperienceModel viewModel;
    private AtSelfWorkExperienceBinding binding;

    private SelfWorkerPublishEntity mEntity;

    private SelfTeamPicAdapter mPicAdapter;
    private List<String> mUploadImgList;
    /**
     * 防止重复上传
     */
    private Map<String, String> mCacheImgMap;
    private int mCurPicNum;

    /**
     * 一级联动数据
     */
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    /**
     * 二级联动数据
     */
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    /**
     * 三级联动数据
     */
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private boolean isLoaded = false;

    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;

    private long startTime = 0;

    private SelfWorkerPublishEntity.WorkExpListBean workExpListBean;
    private SelfWorkerPublishEntity.FilePathBean filePathBean;

    private int currentType = 0;
    private int currentIndex = -1;

    public static void start(Context context, int type, int index) {
        Intent intent = new Intent();
        intent.setClass(context, SelfWorkExperienceActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("index", index);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().
                appComponent(appComponent).selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (currentType == 0) {
            mActionBar.setTitle("工作经验");
            workExpListBean = new SelfWorkerPublishEntity.WorkExpListBean();
        } else {
            mActionBar.setTitle("资格证书");
            binding.etCertificateName.setVisibility(View.VISIBLE);
            binding.etCertificateTime.setVisibility(View.VISIBLE);
            binding.etWorkStartTime.setVisibility(View.GONE);
            binding.etWorkEndTime.setVisibility(View.GONE);
            binding.etArea.setVisibility(View.GONE);
            binding.linWorkDetail.setVisibility(View.GONE);
            filePathBean = new SelfWorkerPublishEntity.FilePathBean();
        }
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.at_self_work_experience);
        binding.setViewModel(null);
        binding.btnCancel.setOnClickListener(this);
        binding.btnEdit.setOnClickListener(this);
        binding.etWorkStartTime.setOnWholeItemClickListener(this);
        binding.etWorkEndTime.setOnWholeItemClickListener(this);
        binding.etArea.setOnWholeItemClickListener(this);
        binding.etCertificateTime.setOnWholeItemClickListener(this);

        currentType = getIntent().getIntExtra("type", 0);
        currentIndex = getIntent().getIntExtra("index", -1);

        initPic();
    }

    @Override
    protected void init() {
        viewModel.getWorkerDetail();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_cancel) {
            finish();
        } else if (id == R.id.btn_edit) {
            if (currentType == 0) {
                if (TextUtils.isEmpty(binding.etWorkStartTime.getContent())) {
                    MToast.showToast(this, binding.etWorkStartTime.getContent_edt().getHint().toString());
                    return;
                }
                if (TextUtils.isEmpty(binding.etWorkEndTime.getContent())) {
                    MToast.showToast(this, binding.etWorkEndTime.getContent_edt().getHint().toString());
                    return;
                }
                if (TextUtils.isEmpty(binding.etArea.getContent())) {
                    MToast.showToast(this, binding.etArea.getContent_edt().getHint().toString());
                    return;
                }
                workExpListBean.setContent(binding.etSelfIntroduction.getEditContent());
            } else {
                if (TextUtils.isEmpty(binding.etCertificateName.getContent())) {
                    MToast.showToast(this, binding.etCertificateName.getContent_edt().getHint().toString());
                    return;
                }
                if (TextUtils.isEmpty(binding.etCertificateTime.getContent())) {
                    MToast.showToast(this, binding.etCertificateTime.getContent_edt().getHint().toString());
                    return;
                }
                filePathBean.setName(binding.etCertificateName.getContent());
            }
            if (mPicAdapter.getRealCount() == 0) {
                MToast.showToast(this, "请上传证书图片");
                return;
            }
            mUploadImgList.clear();
            mCurPicNum = -1;
            uploadPic();
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.et_work_start_time) {
            showTimePop(1);
        } else if (id == R.id.et_work_end_time) {
            showTimePop(2);
        } else if (id == R.id.et_area) {
            if (addressEntityList != null) {
                showCityPop();
            } else {
                viewModel.getAddressModel();
            }
        } else if (id == R.id.et_certificate_time) {
            showTimePop(3);
        }
    }

    private void initPic() {
        mCacheImgMap = new HashMap<>();
        mUploadImgList = new ArrayList<>();
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        binding.rvPic.setLayoutManager(manager);
        mPicAdapter = new SelfTeamPicAdapter(this, new ArrayList<>(), AppConstant.UPLOAD_MAX_SIZE, manager);
        binding.rvPic.setHasFixedSize(false);
        binding.rvPic.addItemDecoration(new GridSpacingItemDecoration(4, ScreenUtils.dip2px(this, 2), false));
        binding.rvPic.setAdapter(mPicAdapter);
        mPicAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                if (TextUtils.isEmpty(s)) {
                    viewModel.pictureSelector(mPicAdapter.hasCount(), PictureConfig.CHOOSE_REQUEST);
                } else {
                    Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) mPicAdapter.getDatas());
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
                    startActivity(intent);
                }
            }
        });
    }

    private void uploadPic() {
        mCurPicNum++;
        int size = mPicAdapter.getRealCount();
        if (size > 0 && mCurPicNum < size) {
            String path = mPicAdapter.getDatas().get(mCurPicNum);
            if (path.startsWith("http")) {
                // 保存已上传图片
                mUploadImgList.add(path);
                uploadPic();
            } else {
                // 过滤已上传的
                if (!TextUtils.isEmpty(mCacheImgMap.get(path))) {
                    mUploadImgList.add(mCacheImgMap.get(path));
                    uploadPic();
                } else {
                    File file = new File(mPicAdapter.getDatas().get(mCurPicNum));
                    viewModel.uploadMultiFileModel(file, mCurPicNum + 1, size);
                }
            }
        } else {
            if (currentType == 0) {
                workExpListBean.setFilePath(mUploadImgList);
                if (currentIndex == -1) {
                    mEntity.getWorkExpList().add(workExpListBean);
                } else {
                    mEntity.getWorkExpList().set(currentIndex, workExpListBean);
                }
            } else {
                filePathBean.setUrl(mUploadImgList);
                if (currentIndex == -1) {
                    mEntity.getFilePath().add(filePathBean);
                } else {
                    mEntity.getFilePath().set(currentIndex, filePathBean);
                }
            }
            viewModel.addWorker(mEntity);
        }
    }

    /**
     * 图片上传回调
     * @param fromString
     * @param toString
     */
    public void uploadPicInfo(String fromString, String toString) {
        mUploadImgList.add(toString);
        mCacheImgMap.put(fromString, toString);
        uploadPic();
    }

    public void updateWorkerEntity(SelfWorkerPublishEntity data) {
        mEntity = data;
        binding.setViewModel(data);
        if (currentType == 0 && data.getWorkExpList().size() > 0 && currentIndex != -1) {
            workExpListBean = data.getWorkExpList().get(currentIndex);
            binding.etWorkStartTime.setContent(DateUtils.timestampToDate(workExpListBean.getStartTime()));
            binding.etWorkEndTime.setContent(DateUtils.timestampToDate(workExpListBean.getEndTime()));
            binding.etArea.setContent(workExpListBean.getProvinceName() + workExpListBean.getCityName() + workExpListBean.getAreaName());
            binding.etSelfIntroduction.setEditContent(workExpListBean.getContent());
            if (workExpListBean.getFilePath() != null && workExpListBean.getFilePath().size() > 0) {
                mPicAdapter.setData(workExpListBean.getFilePath());
            }
        }
        if (currentType == 1 && data.getFilePath().size() > 0 && currentIndex != -1) {
            filePathBean = data.getFilePath().get(currentIndex);
            binding.etCertificateName.setContent(filePathBean.getName());
            binding.etCertificateTime.setContent(DateUtils.timestampToDate(filePathBean.getCollectionTime()));
            if (filePathBean.getUrl() != null && filePathBean.getUrl().size() > 0) {
                mPicAdapter.setData(filePathBean.getUrl());
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                mPicAdapter.setPicData(selectList);
            }
        }
    }

    /**
     * 时间选择器
     * @param flag
     */
    public void showTimePop(int flag) {
        TimePickerBuilder timePickerBuilder = new TimePickerBuilder(SelfWorkExperienceActivity.this, (date, v) -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            String format = sdf.format(date);
            long lt = DateUtils.dateTo10Timestamp(DateUtils.timestampToDate(System.currentTimeMillis()));
            try {
                if (flag == 1) {
                    long times = DateUtils.dateTo13Timestamp(format);
                    long ls = DateUtils.dateTo10Timestamp(DateUtils.timestampToDate(times));
                    if (ls > lt) {
                        MToast.showToast(SelfWorkExperienceActivity.this, "不可大于当前时间");
                        return;
                    }
                    startTime = times;
                    binding.etWorkStartTime.setContent(format);
                    workExpListBean.setStartTime(times);
                }
                if (flag == NumberConstant.NUMBER_TWO) {
                    long times = DateUtils.dateTo13Timestamp(format);
                    long ls = DateUtils.dateTo10Timestamp(DateUtils.timestampToDate(times));
                    long le = DateUtils.dateTo10Timestamp(DateUtils.timestampToDate(startTime));
                    if (ls < le) {
                        MToast.showToast(SelfWorkExperienceActivity.this, "结束时间不能小于开始时间");
                        return;
                    }
                    if (ls > lt) {
                        MToast.showToast(SelfWorkExperienceActivity.this, "结束时间不能大于当前时间");
                        return;
                    }
                    binding.etWorkEndTime.setContent(format);
                    workExpListBean.setEndTime(times);
                }
                if (flag == NumberConstant.NUMBER_THREE) {
                    long times = DateUtils.dateTo13Timestamp(format);
                    long ls = DateUtils.dateTo10Timestamp(DateUtils.timestampToDate(times));
                    if (ls > lt) {
                        MToast.showToast(SelfWorkExperienceActivity.this, "不可大于当前时间");
                        return;
                    }
                    binding.etCertificateTime.setContent(format);
                    filePathBean.setCollectionTime(times);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false});

        Calendar selectedDate = Calendar.getInstance();
        TimePickerView timePicker = timePickerBuilder.build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    /**
     * 所在地区选择
     * @param data
     */
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(SelfWorkExperienceActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                workExpListBean.setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                workExpListBean.setAreaName(areaName);
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.etArea.setContent(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
            workExpListBean.setProvinceName(addressEntityList.get(options1).getName());
            workExpListBean.setProvinceNo(addressEntityList.get(options1).getId());
            workExpListBean.setCityName(opt2.get(options1).get(options2).getName());
            workExpListBean.setCityNo(opt2.get(options1).get(options2).getNo());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        //如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (workExpListBean != null && workExpListBean.getProvinceName() != null && workExpListBean.getProvinceName().equals(addressEntityList.get(x).getName())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (workExpListBean != null) {
            if (workExpListBean.getCityName() != null) {
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (workExpListBean.getCityName().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getName())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            }
            if (workExpListBean.getAreaName() != null) {
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (workExpListBean.getAreaName().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getName())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
            }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    // 发布修改数据成功
    public void editEntitySuccess() {
        WebEvent webEvent = new WebEvent();
        webEvent.setMessageTag(EventConstant.EVENT_WEBVIEW_RELOAD);
        EventBus.getDefault().post(webEvent);
        finish();
    }
}
